//
//  PictureSelectedViewController.swift
//  sinaweiboFirst
//
//  Created by mac on 16/3/18.
//  Copyright © 2016年 mac. All rights reserved.
//

import UIKit
import SnapKit

private let PictureCellID = "PictureCellID"
private let pictureCellMargin: CGFloat = 5
private let coloumImageCount: CGFloat = 3

private let maxImageCount = 3

class PictureSelectedViewController: UICollectionViewController {
    
    var imageList = [UIImage]()
    
    init() {

        let layout = UICollectionViewFlowLayout()
        
        layout.minimumInteritemSpacing = pictureCellMargin
        layout.minimumLineSpacing = pictureCellMargin
        
        let w = (ScreenW - (coloumImageCount + 1) * pictureCellMargin) / coloumImageCount
        layout.itemSize = CGSize(width: w, height: w)
        
        //设置整个section的间距
        layout.sectionInset = UIEdgeInsets(top: pictureCellMargin, left: pictureCellMargin, bottom: 0, right: pictureCellMargin)

         //必须使用super指定的构造函数
        super.init(collectionViewLayout: layout)
        
        self.collectionView?.backgroundColor = UIColor.whiteColor()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.collectionView!.registerClass(PictureSelectedCell.self,forCellWithReuseIdentifier: PictureCellID)
    }
}

extension PictureSelectedViewController {

    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        let detla = imageList.count == maxImageCount ? 0 : 1
        
        return imageList.count + detla
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(PictureCellID, forIndexPath: indexPath) as! PictureSelectedCell
        
        //每实例化一个cell 就让这个控制器成为cell的代理
        cell.selectedDelegate = self
        
        
        if indexPath.item == imageList.count {
        
            cell.image = nil
            
        } else {
        
            cell.image = imageList[indexPath.item]
        }

        cell.backgroundColor = UIColor.randomColor()
        
        return cell
    }
}


// 声明协议
protocol PictureSelectedCellDelegate: NSObjectProtocol {

    //声明协议方法
    func userWillChosePicture()
    
    func userWillDelegatePicture(cell: PictureSelectedCell)
}

//类方法自定义类第一个字母大写 ---> 展示图片自定义的cell
class PictureSelectedCell: UICollectionViewCell {
    
    //代理属性
    weak var selectedDelegate: PictureSelectedCellDelegate?
    
    var image: UIImage? {
    
        didSet {
        
            //如果图片为nil 就隐藏删除按钮
            deleteBtn.hidden = image == nil
            
            addBtn.setImage(image, forState: .Normal)
        }
    }
    
    
    //添加图片的按钮点击事件
    @objc private func addBtnClick() {
        
        if image == nil {
            selectedDelegate?.userWillChosePicture()
        }
    }
    
    @objc private func deleteBtnClick() {
        selectedDelegate?.userWillDelegatePicture(self)
    }
    
    //重写构造方法
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    //默认实现报错
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //MARK: 设置UI界面
    private func setupUI() {
        
        contentView.addSubview(addBtn)
        contentView.addSubview(deleteBtn)
        
        addBtn.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView.snp_edges)
        }
        
        deleteBtn.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(contentView.snp_top)
            make.right.equalTo(contentView.snp_right)
        }
        
        //添加按钮的点击事件
        addBtn.addTarget(self, action: "addBtnClick", forControlEvents: .TouchUpInside)
        deleteBtn.addTarget(self, action: "deleteBtnClick", forControlEvents: .TouchUpInside)
        
        addBtn.imageView?.contentMode = .ScaleAspectFill

        
    }
    
    //MARK: 懒加载子视图
    private lazy var addBtn: UIButton = UIFactory.buttonWithImage(nil, backImageName: "compose_pic_add")

    private lazy var deleteBtn: UIButton = UIFactory.buttonWithImage(nil, backImageName: "compose_photo_close")
}


//实现协议方法 遵守协议 必须的协议方法 在swift中必须实现 不实现默认报错
extension PictureSelectedViewController: PictureSelectedCellDelegate {

    func userWillChosePicture() {
        //选择图片 UIImagePickerController
        let picker = UIImagePickerController()
        
        //指定选择器的代理 
        picker.delegate = self
        
        //允许图片编辑 上传用户头像开启这个属性
//        picker.allowsEditing = true
        
        presentViewController(picker, animated: true, completion: nil)
    }
    
    func userWillDelegatePicture(cell: PictureSelectedCell) {
        
        //根据cell获取点击的indexPath
        if let indexPath = collectionView?.indexPathForCell(cell) {
             //删除数组中对应角标下的元素
            imageList.removeAtIndex(indexPath.item)
            //刷新页面
            collectionView?.reloadData()
        }
        
    }
}

extension PictureSelectedViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {

    // 实现协议方法 图片选择器消失权利交给管理员
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
//        print(image)
//        print(editingInfo)
        
        //将选中的图片保存起来
        imageList.append(image)
        //刷新界面
        collectionView?.reloadData()
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    
}











